package com.example.springai.controller;

import com.google.gson.JsonObject;
import org.json.JSONObject;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

@RestController
@RequestMapping("/ai")
public class BailianAgentRagStreamHttpController {
    public static void main(String[] args) {
        String requestUrl = "https://dashscope.aliyuncs.com/api/v1/apps/7a63af7dec3b4c3db381d3733e3f1736/completion";
        String dashScopeApiKey = "sk-875dd6ef14244431acdc7ccb974f5bfe";
        try {
            URL url = new URL(requestUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            // 请求头
            connection.setRequestProperty("Authorization", "Bearer " + dashScopeApiKey);
            connection.setRequestProperty("Content-Type", "application/json");
            // 设置允许输出
            connection.setDoOutput(true);
            // 构造请求参数

            JSONObject inputNode = new JSONObject();
            inputNode.put("prompt","输出一个java代码  helloword");
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("input",inputNode);
            jsonObject.put("parameters",new JSONObject());
            jsonObject.put("debug",new JSONObject());

            // 写入请求数据
            try (OutputStream os = connection.getOutputStream()) {
                byte[] input = jsonObject.toString().getBytes(StandardCharsets.UTF_8);
                os.write(input, 0, input.length);
            }
            // 获取响应码
            int responseCode = connection.getResponseCode();
            System.out.println("Response Code : " + responseCode);
            // 读取响应数据
            try (BufferedReader br = new BufferedReader(
                    new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
                StringBuilder response = new StringBuilder();
                String responseLine;
                while ((responseLine = br.readLine()) != null) {
                    response.append(responseLine.trim());
                    System.out.println("readLine--------------------"+responseLine+"---------"+responseLine.trim());
                }
                System.out.println("Response Body: " + response.toString());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
